const fs = require('fs-extra');
const path = require('path');
const logger = require('./logger');

class ConfigLoader {
    constructor() {
        this.config = null;
    }

    async load() {
        if (this.config) {
            return this.config;
        }

        const defaultConfigPath = path.join(__dirname, '../../config/default.json');
        const devConfigPath = path.join(__dirname, '../../config/development.json');
        
        let defaultConfig = {};
        let devConfig = {};
        
        try {
            if (await fs.pathExists(defaultConfigPath)) {
                defaultConfig = await fs.readJson(defaultConfigPath);
            }
            
            if (await fs.pathExists(devConfigPath)) {
                devConfig = await fs.readJson(devConfigPath);
            }
        } catch (error) {
            logger.warn('读取配置文件失败:', error);
        }
        
        this.config = {
            ...defaultConfig,
            ...devConfig
        };
        
        return this.config;
    }

    get() {
        if (!this.config) {
            throw new Error('配置未加载，请先调用 load() 方法');
        }
        return this.config;
    }

    async update(newConfig) {
        const devConfigPath = path.join(__dirname, '../../config/development.json');
        await fs.writeJson(devConfigPath, newConfig, { spaces: 2 });
        this.config = { ...this.config, ...newConfig };
        return this.config;
    }
}

module.exports = new ConfigLoader();